package com.miaoxun.controller;

import com.miaoxun.domain.enums.ErrEnum;
import com.miaoxun.domain.exception.ThException;
import com.miaoxun.common.util.UrlPath;
import com.miaoxun.domain.model.ResultModel;
import com.miaoxun.service.init.SqlInit;
import com.miaoxun.web.shiro.ShiroUtils;
import com.miaoxun.web.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${spring.datasource.driver-class-name}")
    String driver;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String userName;
    @Value("${spring.datasource.password}")
    String pwd;

    @ApiOperation(value = "文件上传", notes = "文件名为file")
    @PostMapping(value = "/upload")
    public ResultModel upload(@ApiParam(value = "file", required = true, name = "file") @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String fileName = FileUtil.saveFile(file, "http://" + request.getServerName() + ":" + request.getLocalPort() + File.separator);
        return new ResultModel(ErrEnum.SUCCESS.getCode(), "",fileName);
    }

    @ApiOperation(value = "执行sql文件", notes = "执行sql文件")
    @PostMapping(UrlPath._INIT_SQL)
    public ResultModel initSql(@ApiParam(value = "path") String path) throws Exception {

        if (ShiroUtils.getUserId() == null || ShiroUtils.getUserId() != 1) {
            throw new ThException(ErrEnum.NOPER);
        }

        File file;
        if (null == (path))
            file = ResourceUtils.getFile("classpath:sql.sql");
        else
            file = ResourceUtils.getFile(path);
        SqlInit.execSqlFileByMysql(file, driver, url, userName, pwd);
        return ResultModel.SUCCESS(ErrEnum.SUCCESS.getCode(), ErrEnum.SUCCESS.getMsg());

    }


}
